﻿#region Copyright (c) 2013-04, Olaf Kober <amarok.projects@gmail.com>
//================================================================================
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//================================================================================
#endregion

using System;
using System.Threading.Tasks;


namespace Amarok.Agents
{
	/// <summary>
	/// This type represents a reference to another agent implemented as a weak reference, meaning the referenced 
	/// agent might still get garbage collected even while other agents holding agent references to that agent.
	/// 
	/// An agent reference is intended to be transfered to other agents via messages. Those agents can then use that 
	/// agent reference to post messages back to the referenced agent without keeping that agent in memory. Since the 
	/// agent reference is simply a decorator around <see cref="IAgent"/> it can be used as if you had a direct (strong) 
	/// reference to that agent.
	/// </summary>
	public sealed class AgentReference :
		IAgent
	{
		// data
		private readonly TaskCompletionSource mCompletionSource = new TaskCompletionSource();
		private readonly WeakReference mWeakReference;


		#region ++ ICompletable Interface ++

		/// <summary>
		/// Gets a Task instance that represents the completion state of the object. This task instance is 
		/// transitioned into the final RunToCompletion state when the object has finally completed.
		/// </summary>
		public Task Completion
		{
			get
			{
				var agent = this.Target;

				if (agent == null)
					mCompletionSource.SignalCompletion();

				return mCompletionSource.Task;
			}
		}

		/// <summary>
		/// Initiates the asynchronous completion of the object. After calling this method the object will complete 
		/// and its <see cref="Completion"/> task will enter a final state after it has processed or discarded all 
		/// previously available messages.
		/// 
		/// Completing this agent reference does not complete the referenced agent, it just releases the reference 
		/// to that agent.
		/// </summary>
		/// 
		/// <param name="discardAvailableMessages">
		/// True to discard all already available messages. False to process all already available messages to 
		/// completion. Defaults to false.</param>
		public void Complete(Boolean discardAvailableMessages = false)
		{
			mWeakReference.Target = null;
			mCompletionSource.SignalCompletion();
		}

		#endregion

		#region ++ IDisposable Interface ++

		/// <summary>
		/// When calling <see cref="IDisposable.Dispose"/> all available messages will be discarded and the method 
		/// will block the calling thread until the object has finally completed.
		/// 
		/// Disposing this agent reference does not dispose the referenced agent, it just releases the reference 
		/// to that agent.
		/// </summary>
		public void Dispose()
		{
			this.Complete(discardAvailableMessages: true);
		}

		#endregion

		#region ++ IDispatcher Interface ++

		/// <summary>
		/// Posts the message to the dispatcher.
		/// 
		/// The method stores the supplied message in the dispatcher's input message queues of interested consumers and 
		/// returns immediately, meaning it only schedules the message for further processing, but the actual processing 
		/// is done later in other threads.
		/// 
		/// Messages that the dispatcher is unable to handle, i.e. because no corresponding message handler exists, 
		/// will be dropped silently.
		/// 
		/// If there is no interested consumer at the time of posting, then the message will be dropped silently.
		/// 
		/// Messages that are posted after completing the dispatcher will be dropped silently.
		/// </summary>
		/// 
		/// <param name="message">
		/// The message that should be posted.</param>
		/// 
		/// <returns>
		/// A boolean value indicating whether the message being posted has been scheduled for further processing, or 
		/// False, if the message has been filter, the dispatcher is completing or already completed, or no matching 
		/// message handler exists.
		/// </returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		public Boolean Post(Message message)
		{
			Verify.NotNull(message, "message");

			var agent = this.Target;

			if (agent == null)
			{
				mCompletionSource.SignalCompletion();
				return false;
			}
			else
			{
				return agent.Post(message);
			}
		}

		#endregion

		#region ++ IAdvertiser Interface ++

		/// <summary>
		/// Subscribes the supplied agent on the publisher. All messages published that match or derive 
		/// from the specified message type and that pass the optional message filter will be forwarded 
		/// to the subscriber.
		/// </summary>
		/// 
		/// <param name="messageType">
		/// The base type of messages for which to subscribe. This type must be assignable to <see cref="Message"/>.</param>
		/// <param name="subscriber">
		/// An agent reference to the agent subscribing for messages.</param>
		/// <param name="messageFilter">
		/// A callback used as content-based filter. Optional, defaults to null.</param>
		/// 
		/// <returns>
		/// An object representing the subscription that can be used to unsubscribe from the publisher, 
		/// or a null value when the advertiser has already be completed.</returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="ArgumentException">
		/// A value was passed to a method that did not accept it as a valid argument, because 
		/// the value representing a type is not assignable to the specified target type.</exception>
		public ICompletable Subscribe(Type messageType, AgentReference subscriber, Predicate<Message> messageFilter = null)
		{
			Verify.IsAssignableTo(messageType, typeof(Message), "messageType");
			Verify.NotNull(subscriber, "subscriber");

			var agent = this.Target;

			if (agent == null)
			{
				mCompletionSource.SignalCompletion();
				return null;
			}
			else
			{
				return agent.Subscribe(messageType, subscriber, messageFilter);
			}
		}

		/// <summary>
		/// Subscribes the supplied callback on the publisher. All messages published that match or derive 
		/// from the specified message type and that pass the optional message filter will be forwarded 
		/// to the subscriber.
		/// </summary>
		/// 
		/// <param name="messageType">
		/// The base type of messages for which to subscribe. This type must be assignable to <see cref="Message"/>.</param>
		/// <param name="subscriber">
		/// A callback subscribing for messages.</param>
		/// <param name="messageFilter">
		/// A callback used as content-based filter. Optional, defaults to null.</param>
		/// 
		/// <returns>
		/// An object representing the subscription that can be used to unsubscribe from the publisher, 
		/// or a null value when the advertiser has already be completed.
		/// </returns>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		/// <exception cref="ArgumentException">
		/// A value was passed to a method that did not accept it as a valid argument, because 
		/// the value representing a type is not assignable to the specified target type.</exception>
		public ICompletable Subscribe(Type messageType, Action<Message> subscriber, Predicate<Message> messageFilter = null)
		{
			Verify.IsAssignableTo(messageType, typeof(Message), "messageType");
			Verify.NotNull(subscriber, "subscriber");

			var agent = this.Target;

			if (agent == null)
			{
				mCompletionSource.SignalCompletion();
				return null;
			}
			else
			{
				return agent.Subscribe(messageType, subscriber, messageFilter);
			}
		}

		#endregion

		#region ++ Public Interface ++

		/// <summary>
		/// Gets a boolean value indicating whether the agent referenced by the current agent reference has been 
		/// garbage collected.
		/// 
		/// Because an object could potentially be reclaimed for garbage collection immediately after the property 
		/// returns true, using this property is not recommended unless you are testing only for a false return value.
		/// </summary>
		public Boolean IsAlive
		{
			get
			{
				return mWeakReference.IsAlive;
			}
		}

		/// <summary>
		/// Gets the agent object referenced by this agent reference. This property might return null, if the agent 
		/// referenced has been already garbage collected. This property returns a new strong reference to the 
		/// referenced agent. Be sure to null out this reference after use.
		/// </summary>
		public IAgent Target
		{
			get
			{
				return mWeakReference.Target as IAgent;
			}
		}


		/// <summary>
		/// Initializes a new instance.
		/// </summary>
		/// 
		/// <param name="agent">
		/// The agent to which a weak agent reference should be created.</param>
		/// 
		/// <exception cref="ArgumentNullException">
		/// A null reference was passed to a method that did not accept it as a valid argument.</exception>
		public AgentReference(IAgent agent)
		{
			Verify.NotNull(agent, "agent");
			mWeakReference = new WeakReference(agent, false);
		}

		#endregion

	}
}
